package com.zky.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zky.basic.dto.AccountDto;
import com.zky.basic.exception.BusinessException;
import com.zky.basic.jwt.JwtUtils;
import com.zky.basic.jwt.LoginData;
import com.zky.basic.jwt.RsaUtils;
import com.zky.system.domain.Menu;
import com.zky.system.domain.Permission;
import com.zky.user.constants.WxConstants;
import com.zky.user.domain.Logininfo;
import com.zky.user.domain.User;
import com.zky.user.domain.Wxuser;
import com.zky.user.mapper.LogininfoMapper;
import com.zky.user.mapper.UserMapper;
import com.zky.user.mapper.WxuserMapper;
import com.zky.user.service.ILogininfoService;
import com.zky.basic.service.impl.BaseServiceImpl;
import com.zky.util.AjaxResult;
import com.zky.util.HttpUtil;
import com.zky.util.Md5Utils;
import com.zky.util.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> loginAccount(AccountDto accountDto) {
        //校验空值
        if (StringUtils.isEmpty(accountDto.getAccount()) || StringUtils.isEmpty(accountDto.getCheckPass())){
            throw new BusinessException("信息不能为空");
        }
        //检验是否有用户
        Logininfo logininfo = logininfoMapper.findByAccount(accountDto);
        if (logininfo==null){
            throw new BusinessException("用户名错误");
        }
        //校验密码是否正确
        String md5pwd = Md5Utils.encrypByMd5(accountDto.getCheckPass() + logininfo.getSalt());
        if(!md5pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }
        //校验是否启用
        if (!logininfo.getDisable()){
            throw new BusinessException("当前用户已被禁用，请联系管理员");
        }

        return loginSuccessJwtHandler(logininfo);
    }

    @Override
    public AjaxResult loginWechat(Map<String, String> map) {
        //发送第二个请求，需要code，openid，secret
        //1.准备第二个请求的地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));

        //2.使用工具类发送请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //通过fastjson将json转成对象 获取token和openid
        JSONObject object = JSONObject.parseObject(jsonStr);
        String access_token = object.getString("access_token");
        String openid = object.getString("openid");

        //4.通过openid查询wxuser
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //代表绑定过
        if (wxuser!=null){
            User user = userMapper.findOne(wxuser.getUserId());
            //说明绑定了
            if (user!=null){
                Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());

                Map<String, Object> requestMap = loginSuccessJwtHandler(logininfo);


                return new AjaxResult(true,requestMap);

            }
        }
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {

        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");

        String accessToken = map.get("accessToken");

        String openId = map.get("openId");

        //1.校验-空值
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
        //2.校验-手机验证码：是否过期，是否正确

        //判断验证码是否过期
        Object obj = redisTemplate.opsForValue().get("phone:" + phone);
        if (obj==null){
            throw new BusinessException("验证码过期，请重新获取");
        }
        if (!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("验证码错误");
        }
        //3.准备第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);

        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换WxUser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //6.创建User对象和Logininfo对象【phone】 - 难度
        User user = userMapper.findByPhone(phone);
        if(user==null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);

        }

        //8.做免密登录
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());

        Map<String, Object> map1 = loginSuccessJwtHandler(logininfo);


        return AjaxResult.me().setObj(map1);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32).toString();
        String randomPwd = StrUtils.getRandomString(6);
        String md5pwd = Md5Utils.encrypByMd5(salt + randomPwd);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;

    }

    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        //设置logininfo
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        //判断是否是管理员
        if (logininfo.getType()==0){
           List<String> permissions = logininfoMapper.findPermissionByLogininfoId(logininfo.getId());
           map.put("permissions",permissions);
           loginData.setPermissions(permissions);

           List<Menu> menus = logininfoMapper.findMenuByLogininfoId(logininfo.getId());
           map.put("menus",menus);
           loginData.setMenus(menus);

        }
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }

    return map;
    }


}
